package com.concurrent.shiro;

import com.concurrent.dao.RoleMapper;
import com.concurrent.dao.UserMapper;
import com.concurrent.dao.UserRoleMapper;
import com.concurrent.model.User;
import com.concurrent.model.UserRole;
import com.concurrent.util.SpringContextHolder;
import org.apache.shiro.authc.CredentialsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class ShiroFactroy implements IShiro{

@Autowired
    UserMapper userMapper;
@Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleMapper roleMapper;
    public static IShiro me() {
        return SpringContextHolder.getBean(IShiro.class);
    }
    @Override
    public User user(String username) {
        User user=userMapper.getUser(username);
        if(null==user){
            throw new CredentialsException();
        }
        return user;
    }
    @Override
    public  List<String> getRoles(String username){
        User user=userMapper.getUser(username);
        List<UserRole> userRoles = userRoleMapper.selectRoleByUsername(user.getId());
        List<String> roleList = new ArrayList<>();
        for(UserRole userRole:userRoles){
            roleList.add(roleMapper.selectById(userRole.getRid()).getName());
        }
        return roleList;
    }
}
